package net.oschina.jhssm.common.controller;

import net.oschina.jhssm.common.util.JsonUtil;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import javax.validation.ValidationException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ZhaoJinBing on 2017/6/20.
 */
public class BaseController {

    /**
     * 参数检查
     * @param result
     */
    protected void checkBindingResult(BindingResult result) {
        if (result.hasErrors()){
            List<Map<String, Object>> errorMapList = new ArrayList<>();
            for (FieldError fieldError : result.getFieldErrors()) {
                Map<String, Object> errorMap = new HashMap<>();
                errorMap.put("field", fieldError.getField());
                errorMap.put("message", fieldError.getDefaultMessage());
                errorMapList.add(errorMap);
            }
            throw new ValidationException(JsonUtil.toJsonString(errorMapList));
        }
    }
}
